//
//  UserController.swift
//  foreign_swift
//
//  Created by 黄敦仁 on 15/4/22.
//  Copyright (c) 2015年 hdr. All rights reserved.
//

import UIKit
import SMGridView




class UserController: UIViewController,SMGridViewDataSource,SMGridViewDelegate{
    let columnCnt = 4
    
    let requst_user_mark = "requst_user_mark"
    var users:[User]=[User]()
    
    
    @IBOutlet var curUserAccountLabel: UILabel!
    @IBOutlet var curUserNameLabel: UILabel!
    @IBOutlet var curUserAvatarIv: UIImageView!
    @IBOutlet var gridView: SMGridView!
    @IBOutlet var curUserBar: UIView!
    @IBOutlet var logoutBtn: UIButton!

    init() {
        super.init(nibName: "UserList", bundle: nil)
        super.title = "我"
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if Config.shareInstance().getBoolValueKey(requst_user_mark) {
            setupUserList()
        }else{
            Http.get(Urls.userList).success(onUserListBack)
            .showProgress(self)
        }
        
        let tapGesture = UITapGestureRecognizer(target: self, action: "onUserBarClick")
        self.curUserBar.addGestureRecognizer(tapGesture)
        
        gridView.vertical = true
        gridView.dataSource = self
        gridView.delegate = self
        
        if let avatarUrl = CurUser.avatar {
            curUserAvatarIv.sd_setImageWithURL(NSURL(string: avatarUrl))
        }
        curUserNameLabel.text = CurUser.name
        curUserAccountLabel.text = CurUser.email
        
        setupUserList()
        
        ViewHelper.changeToRedButton(logoutBtn)
    }
    
    func onUserBarClick(){
        println("点击了userbar")
    }
    
    
    func onUserListBack(data:JSON){
                println(data)
        let groups = data["group_names"].arrayValue
        if let unregisterGroup = groups?[0].arrayValue {
            for (i,userJson) in enumerate(unregisterGroup) {
                if i == 0 {
                    continue
                }
                let user = Converter.jsonToUser(userJson)
                user.userType = Const.USER_TYPE_UNREGISTERED
                YolandaDb.saveUser(user)
            }
        }
        
        if let registerGroup = groups?[1].arrayValue {
            for (i,userJson) in enumerate(registerGroup) {
                if i == 0 {
                    continue
                }
                let user = Converter.jsonToUser(userJson)
                user.userType = Const.USER_TYPE_REGISTERED
                YolandaDb.saveUser(user)
            }
        }
        Config.shareInstance().setValue(true, forKey: requst_user_mark)
        setupUserList()
    }
    
    func setupUserList(){
        users = YolandaDb.getAllUser()
        gridView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /**
    @return Number of items in a section
    @param gridView The calling SMGridView
    @param section The asked section
    */
    func smGridView(gridView: SMGridView!, numberOfItemsInSection section: Int) -> Int{
       /*
        let userCnt = users.count
        if section * columnCnt < userCnt {
            return columnCnt
        }else{
            return userCnt % section
        }*/
        return users.count
    }
    
    func smGridView(gridView: SMGridView!, numberOfRowsInSection section: Int) -> Int{
        return columnCnt
    }
    
    func smGridViewSameSize(gridView: SMGridView!) -> Bool{
            return true
    }
    
    
    /**
    @return Size of a view in a given indexPath
    @param gridView The calling SMGridView
    @param indexPath The target indexPath
    */
    func smGridView(gridView: SMGridView!, sizeForIndexPath indexPath: NSIndexPath!) -> CGSize{
        return CGSize(width: (Const.screen_width-20)/4, height: 80)
    }
    
    /**
    You should use dequeReusableView or dequeReusableViewWithClass: inside this method for better performance
    
    @return Size of a view in a given indexPath
    @param gridView The calling SMGridView
    @param indexPath The target indexPath
    */
    func smGridView(gridView: SMGridView!, viewForIndexPath indexPath: NSIndexPath!) -> UIView!{
        var itemView = gridView.dequeReusableView() as? UserGridItemView
        if itemView == nil {
            itemView = UINib(nibName: "UserGridItemView", bundle: nil).instantiateWithOwner(nil, options: nil).first as! UserGridItemView
        }
        let user = users[indexPath.row]
        itemView?.nameLabel.text = user.name
        let defaultImage = UIImage(named: user.gender == 0 ? "common_headPortraitDefault_male.png":"common_headPortraitDefault_female.png")

        if let avatarUrl = user.avatar {
            itemView?.avatarIv.sd_setImageWithURL(NSURL(string: avatarUrl), placeholderImage: defaultImage)
        }else{
            itemView?.avatarIv.image = defaultImage
        }
        return itemView
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
*/
    

}
